package com.demo.gulimall.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.gulimall.common.utils.R;
import com.demo.gulimall.seckill.entity.SeckillSession;
import com.demo.gulimall.seckill.entity.SeckillSkuRelation;
import com.demo.gulimall.seckill.mapper.SeckillSessionMapper;
import com.demo.gulimall.seckill.service.SeckillSessionService;
import com.demo.gulimall.seckill.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 秒杀活动场次
 *
 * @author Chen Yuan
 */

@Service
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionMapper, SeckillSession> implements SeckillSessionService {

    @Autowired
    private SeckillSessionMapper seckillSessionMapper;

    @Autowired
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public List<SeckillSession> getLatestThreeDaySession(){
        // 计算当前以及三天后的日期
        LocalDate now = LocalDate.now();
        LocalDate plus2 = now.plusDays(2);

        LocalTime minTime = LocalTime.MIN;
        LocalTime maxTime = LocalTime.MAX;

        LocalDateTime start = LocalDateTime.of(now, minTime);
        LocalDateTime end = LocalDateTime.of(plus2, maxTime);

        String startStr = start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endStr = end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        List<SeckillSession> sessionList = this.list(new QueryWrapper<SeckillSession>().between("start_time", startStr, endStr));

        if (sessionList != null && sessionList.size() > 0) {
            sessionList = sessionList.stream().map(session -> {
                Long sessionId = session.getId();
                List<SeckillSkuRelation> relations = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelation>().eq("promotion_session_id", sessionId));
                session.setRelations(relations);
                return session;
            }).collect(Collectors.toList());
        }

        return sessionList;
    }
}
